import os
import shutil
import subprocess
import sys
import argparse

def getcodefromgitee(folder,update=False):
    """
    从Gitee克隆指定包名的代码库到当前目录下的folder文件夹
    
    参数:
        folder: 包名，也是仓库名，同时将作为本地目录名
        update: 是否更新已下载的代码库
    """
    # 构建仓库URL - 格式为 https://gitee.com/agiros/pkgname
    repo_url = f"https://gitee.com/agiros/{folder}"
    
    # 获取当前工作目录
    current_dir = os.getcwd()
    target_dir = os.path.join(current_dir, folder)
    
    # 检查目录是否已存在，从git仓库更新代码到本地仓库
    if os.path.exists(target_dir):
        print(f"⚠️ 目录已存在: {target_dir}")
        if update: 
            try:
                print(f"正在更新 {target_dir} 中的代码...")
                subprocess.run(['git', 'pull'], cwd=target_dir, check=True)
                print(f"✅ 更新成功")
                return True
            except subprocess.CalledProcessError as e:
                print(f"❌ 更新失败: {str(e)}")
    
    # 执行git克隆命令
    print(f"准备从 {repo_url} 克隆仓库")
    branch = "master"
    clone_cmd = ['git', 'clone', '-b', branch, repo_url, folder]
    travodds_branch = "master-agiros"
    travodds_clone_cmd = ['git', 'clone', '-b', travodds_branch, repo_url, folder]

    try:
        #folder名字中包含travodds字样的，使用travodds_clone_cmd
        if "travodds" in folder:
            print(f"正在克隆 {repo_url} 的分支 {travodds_branch}...")
            subprocess.run(travodds_clone_cmd, check=True)
            print(f"✅ 成功克隆到 {target_dir}")
            return True
        else:
            print(f"正在克隆 {repo_url} 的分支 {branch}...")
            subprocess.run(clone_cmd, check=True)
            print(f"✅ 成功克隆到 {target_dir}")
            return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 克隆失败: {str(e)}")
        if e.stderr:
            print(f"错误输出: {e.stderr.decode().strip()}")
        return False
    except Exception as e:
        print(f"❌ 克隆过程中出错: {str(e)}")
        return False


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='从Gitee下载仓库')
    parser.add_argument('-r', '--repos', default=os.path.join(os.getcwd(), 'repos.conf'), help='repos.conf文件路径 (默认: 当前目录下的repos.conf)')
    parser.add_argument('-d', '--targetbase', default=os.path.join(os.getcwd(), 'downloads'), help='下载目录路径 (默认: 当前目录下的downloads目录)')
    parser.add_argument('--update', action='store_true', help='是否更新已下载的代码库 (默认: 不更新)')

    args = parser.parse_args()

    with open(args.repos, 'r', encoding='utf-8-sig') as f:
        repo_path = [line.strip() for line in f.readlines()]
    
    os.makedirs(args.targetbase, exist_ok=True)
    os.chdir(args.targetbase)
    
    total_repos = len(repo_path)
    success_count = 0
    fail_count = 0
    existing_count = 0
    update_success_count = 0
    update_fail_count = 0

    # 检查是否安装git，没有安装的话先安装
    if shutil.which('git') is None:
        print("⚠️ Git 未安装，正在安装...")
        try:
            subprocess.run(['yum', 'install', '-y', 'git'], check=True)
            print("✅ Git 安装成功")
        except subprocess.CalledProcessError as e:
            print("❌ Git 安装失败:", e)
            sys.exit(1)
    else:
        print("✅ Git 已安装")
    
    print("开始下载仓库...")

    for index, repo in enumerate(repo_path, start=1):
        print(f"\n===== 处理仓库 {index}/{total_repos}：{repo} =====")
        if not os.path.exists(repo):
            print(f"⚠️ 缺失代码{repo}，从gitee下载")
            result = getcodefromgitee(repo)
            if result:
                success_count += 1
            else:
                fail_count += 1
        else:
            existing_count += 1
            if args.update: 
                print(f"⚠️ 仓库 {repo} 已存在，准备更新...")
                result = getcodefromgitee(repo,args.update)
                if result:
                    update_success_count += 1
                else:
                    update_fail_count += 1

    
    print(f"\n===== 下载统计 =====")
    print(f"总仓库数: {total_repos}")
    print(f"成功下载: {success_count}")
    print(f"下载失败: {fail_count}")
    print(f"已存在仓库: {existing_count}")
    print(f"成功更新: {update_success_count}")
    print(f"更新失败: {update_fail_count}")
    print(f"\n")



